<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\goods\controller;

use think\Db;
use cmf\controller\HomeBaseController;
use app\goods\model\GoodsCategoryModel;
use app\goods\model\GoodsModel;

class SearchController extends HomeBaseController
{
    //default模版，搜索结果页面
    public function index() {
        $goodsModel         = new GoodsModel();
        $goodsCategoryModel = new GoodsCategoryModel();

        $keyword = $this->request->param('keyword/s','');
        $all     = $this->request->param('all/d',0);
        $cid     = $id = $cat_id = $this->request->param('cid/d',14);

        if( $all === 1 ){
            $cat_id = 14;
            $cid = $id = db('GoodsCategory')->where('parent_id=14')->limit(1)->value('id');
        }

        $start   = $this->request->param('start',0,'intval');
        $size    = $this->request->param('size',8,'intval');
        $limit   = $start.','.$size;

        $filter_attr_str = isset($_REQUEST['filter_attr']) ? htmlspecialchars(trim($_REQUEST['filter_attr'])) : '0';
        $filter_attr_str = trim(urldecode($filter_attr_str));
        $filter_attr_str = preg_match('/^[\d\._]+$/',$filter_attr_str) ? $filter_attr_str : '';  //
        $filter_attr     = empty($filter_attr_str) ? '' : explode('.', $filter_attr_str);

        // pre($_REQUEST);

        //当前分类信息
        $term        = $goodsCategoryModel->field('path,filter_attr')->find($id);
        $path_count  = substr_count($term['path'],'-'); //每条横线代表一级，如两条，则该分类为二级分类

        $level = 3; //分类级数
        if( $all!==1 ){
            //若当前分类不满足分类级数
            if( $path_count < $level ){
                //递归查询子分类,直到子分类达到分类级数
                $cat_id = $id = $this->_getSubTermId($id, $level);
            }
        }
        // echo $id;die;

        //利用面包屑查询，得到当前分类的父层级关系
        $bread_where = array('parent_id'=>array('NEQ',0));     //查询条件，不需查询顶级分类
        $b_limit     = $level - 1;
        $bread       = cmf_get_goods_breadcrumb($id, 1, "limit:$b_limit;", $bread_where);

        // pre($bread,1);
        
        //查询面包屑各层级的子分类，构建筛选面板分类数据
        $name_arr = array('行业', '产品', '分类');
        foreach ($bread as $k => $v) {
            $terms[$k]['name']     = empty($name_arr[$k]) ? $terms[$k-1]['name'] : $name_arr[$k] ;
            if( $all !== 1 ){
                $terms[$k]['selected'] = $v['id'];
            }
            $terms[$k]['child']    = cmf_get_goods_child_terms($v['parent_id']);
        }

        $children     = get_children($id);

        if( $cid != $id ){
            $term = $goodsCategoryModel->field('path,filter_attr')->find($id);
        }

        // if ( !empty($term['filter_attr']) )
        // {
        //     $term_filter_attr = explode(',', $term['filter_attr']);       //提取出此分类的筛选属性
        //     // $this->assign('filter_attr_count_num',count($term_filter_attr));

        //     $all_attr_list = array();
        //     foreach ($term_filter_attr AS $k => $v)
        //     {
        //         $attr_info                = db('Attribute')->field('attr_id,attr_name,attr_values')->find($v);
        //         $attr_info['attr_values'] = str_replace("\r\n", "\n", $attr_info['attr_values']);
        //         $attr_info['attr_values'] = explode("\n",$attr_info['attr_values']);

        //         $all_attr_list[]          = $attr_info;
        //     }
        // }

        /* 属性筛选 */
        $ext = ''; //商品查询条件扩展

        if ($term['filter_attr'] > 0 && $all !== 1) {
            $term_filter_attr = $term['filter_attr'];     //提取出此分类的筛选属性

            $all_attr_list = array();
            foreach ($term_filter_attr AS $key => $value) {

                $temp_name = Db::table('__GOODS_ATTRIBUTE__ a, __GOODS_ATTR__ ga, __GOODS__ g ,__GOODS_CATEGORY_RELATE__ category_relate')
                          -> where("$children AND a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND category_relate.goods_id = g.goods_id AND g.post_status = 99 AND a.attr_id='$value'")
                          -> value('a.attr_name');
                
                if( $temp_name ){
                    $all_attr_list[$key]['filter_attr_name'] = $temp_name;
                    
                    $attr_list = Db::table('__GOODS_ATTR__ ga, __GOODS__ g, __GOODS_CATEGORY_RELATE__ category_relate')
                              -> field("ga.attr_id, MIN(ga.goods_attr_id ) AS goods_id, ga.attr_value AS attr_value")
                              -> where("$children AND g.goods_id = ga.goods_id AND category_relate.goods_id = g.goods_id AND g.post_status = 99 AND ga.attr_id='$value'")
                              -> group('ga.attr_value')
                              -> select();

                    
                    //获取当前url中已选择属性的值，并保留在数组中
                    $temp_arrt_url_arr = array();
                    for ($i = 0; $i < count($term_filter_attr); $i++) {
                        $temp_arrt_url_arr[$i] = !empty($filter_attr[$i]) ? $filter_attr[$i] : 0;
                    }


                    foreach ($attr_list as $k => $v)
                    {
                        $temp_arrt_url_arr[$key] = $v['goods_id'];       //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串
                        $temp_arrt_url           = implode('.', $temp_arrt_url_arr);

                        $all_attr_list[$key]['attr_list'][$k]['attr_value']  = $v['attr_value'];
                        $all_attr_list[$key]['attr_list'][$k]['filter_attr'] = $temp_arrt_url;
                        $all_attr_list[$key]['attr_list'][$k]['goods_id']    = $v['goods_id'];

                        $filter_attr_name[$key][$v['goods_id']]=$v['attr_value'];

                        if (!empty($filter_attr[$key]) AND $filter_attr[$key] == $v['goods_id'])
                        {
                            $all_attr_list[$key]['attr_list'][$k]['selected'] = 1;
                        }
                        else
                        {
                            $all_attr_list[$key]['attr_list'][$k]['selected'] = 0;
                        }
                    }
                }
            }
            // pre($all_attr_list,1);

            // foreach ($filter_attr AS $fkey=>$fval)
            // {
            //     if ($fval)
            //     {
            //         $cond_name = "";
            //         $filter_attr_temp = $filter_attr;
            //         $filter_attr_temp[$fkey]='0';
            //         $temp_arrt_url_hunuo =implode(".", $filter_attr_temp);
            //         if (strstr($fval, "_"))
            //         {
            //             $fval_array = explode("_", $fval);
            //             foreach ($fval_array AS $fval_key=> $fval_hunuo)
            //             {
            //                 $cond_name .= ($fval_key ? "，" : "") . $filter_attr_name[$fkey][$fval_hunuo];
            //             }
            //         }
            //         else
            //         {
            //             $cond_name = $filter_attr_name[$fkey][$fval];
            //         }
            //         $condition[]=array(
            //                 'cond_type' =>$all_attr_list[$fkey]['filter_attr_name'],
            //                 'cond_name' =>$cond_name,
            //                 'cond_url' =>build_uri('category', array('cid'=>$id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url_hunuo, 'filter'=>$filter), $term['cat_name'])
            //             );
            //     }
            // }
    
            $this->assign('filter_attr_list',  $all_attr_list);

            // pre($filter_attr);
            $id_arr = array();
            /* 扩展商品查询条件 */
            if (!empty($filter_attr))
            {
                $ext_group_goods = array();

                foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
                {
                    if (strstr($v, '_') && $v !=0 && isset($term_filter_attr[$k]) ) {
                        $attr_sql = str_replace("_", ",", $v);
                        $where    = array(
                            'b.attr_id'       => $term_filter_attr[$k],
                            'a.goods_attr_id' => array('IN',$attr_sql),
                        );
                    } elseif (is_numeric($v) && $v !=0 &&isset($term_filter_attr[$k])) {
                        $where = array(
                            'b.attr_id'       => $term_filter_attr[$k],
                            'a.goods_attr_id' => $v,
                        );
                    }

                    $ext_group_goods = db('GoodsAttr')
                                    -> alias('a')
                                    -> join('__GOODS_ATTR__ b ', 'b.attr_value = a.attr_value')
                                    -> where($where)
                                    -> field('DISTINCT(b.goods_id)')
                                    -> select();
                    // pre($ext_group_goods);
                    // foreach ($ext_group_goods as $key => $value) {
                    //     $id_arr[$value['goods_id']] = $value['goods_id'];
                    // }

                    $id_arr = array();
                    foreach ($ext_group_goods as $key => $value) {
                        $id_arr[] = $value['goods_id'];
                    }

                    $ext .= ' AND ' . db_create_in($id_arr, 'g.goods_id');
                }
            }
        }

        //查询产品
        // $goods_where = "category_relate.id ".db_create_in($children);
        $goods_where = '';
        if( !empty($children) && $all !== 1 ){
            $goods_where = $children;
        }

        if( !empty($id_arr) ){
            $goods_where .= $ext;
        }
        // echo $goods_where;die;

        if( !empty($keyword) ){
            if(!empty($goods_where)){
                 $goods_where.=' AND ';
            }
            $goods_where.= "(goods_name LIKE '%$keyword%' OR post_keywords LIKE '%$keyword%' OR charac LIKE '%$keyword%')";
        }

        // echo $goods_where;die;

        //数据总数

        //查询数据集
        $lists = $goodsModel
              -> alias("g")
              -> field('goods_name,g.goods_id,g.more,post_excerpt,category_id')
              -> join("__GOODS_CATEGORY_RELATE__ category_relate", "g.goods_id = category_relate.goods_id",'LEFT')
              -> join('__GOODS_CATEGORY__ category', 'category_relate.category_id = category.id')
              -> where($goods_where)
              -> where('category_relate.is_show',1)
              -> where('g.delete_time',0)
              -> limit($limit)
              -> order(GSO)
              -> select();

        if( !$this->request->isAjax() ){
            $count = $goodsModel
                  -> alias("g")
                  -> field('goods_name,g.goods_id,g.more,post_excerpt,category_id')
                  -> join("__GOODS_CATEGORY_RELATE__ category_relate", "g.goods_id = category_relate.goods_id",'LEFT')
                  -> join('__GOODS_CATEGORY__ category', 'category_relate.category_id = category.id')
                  -> where($goods_where)
                  -> where('category_relate.is_show',1)
                  -> where('g.delete_time',0)
                  -> count();
        }
        // pre($lists);
        // pre($goods);
        // die;

        // pre($cat_id);
        // pre($cid);

        $this -> assign("all", $all);
        $this -> assign("cat_id", $cat_id); //用于前台面包屑
        $this -> assign("terms", $terms);
        $this -> assign("id", $id);
        $this -> assign("cid", $cid);
        $this -> assign("filter_attr_list", $all_attr_list);
        $this -> assign("lists", $lists);
        $this -> assign("keyword", $keyword);
        $this -> assign("filter_attr_str", $filter_attr_str);
        $this -> assign("count", $count);
        $this -> assign("page_size", $size);

        if( $this->request->isAjax() ){
            //使用的模版
            $html = $this->fetch('search_ajax');

            //是否存在更多数据
            $more_limit = $start+$size.',1';
            $more_data  = $goodsModel
                       -> alias("g")
                       -> field('g.goods_id')
                       -> join("__GOODS_CATEGORY_RELATE__ category_relate", "g.goods_id = category_relate.goods_id",'LEFT')
                       -> join('__GOODS_CATEGORY__ category', 'category_relate.category_id = category.id')
                       -> where($goods_where)
                       -> where('category.is_show',1)
                       -> limit($more_limit)
                       -> order(GSO)
                       -> select()
                       -> toArray();

            $return = array(
                'error'     => 0,
                'data'      => $html,
                'start'     => $start,
                'size'      => $size,
                'more_data' => empty($more_data) ? 0 : 1 ,
            );
            return $return;
        }else{
            return $this->fetch('/search');
        }
    }
    
    /**
     * 递归查子分类id
     * @param  int $id  当前分类的id
     * @param  int $level    查询到子分类的级数
     * @return int           子分类id
     */
    public function _getSubTermId($id, $level=1){
        $term_info = db("GoodsCategory")
                  -> field('id,parent_id,path')
                  -> where( array('parent_id'=>$id) )
                  -> order('list_order ASC')
                  -> find();

        //二级分类下是否存在三级分类
        if( !empty($term_info['id']) ){
            $id    = $term_info['id'];
            //每条横线代表一级，如两条，则该分类为二级分类
            $path_count = substr_count($term_info['path'],'-'); 

            if( $path_count < $level){
                $id = $this->_getSubTermId($term_info['id']);
            }
        }
    
        return $id;
    }
}

/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $term_id        指定的分类ID
 * @param   string      $ext        表的前缀名称
 * @return  string
 */
function get_children($category_id = 0,$ext='category_relate')
{
    $category_id = intval($category_id);
    
    $terms = db("GoodsCategory")
          -> where("status=1 and path like '%-$category_id-%'")
          -> where('is_show',1)
          -> order("list_order asc")
          -> column('id');
    $terms = empty($terms)? array() : $terms ;

    // return array_unique( array_merge(array($category_id), $terms)) ;
    return $ext.'.category_id ' . db_create_in(array_unique( array_merge(array($category_id), $terms) ));
}
